package zj.http;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import zj.pojo.ZjObject;
import zj.utils.ZjFinal;

/**
 * Created by wjw on 2017/5/28.
 */

public class ZjHttpRequest {
    public static JSONObject post(ZjObject zjObject){
        String str_url = String.format("http://%s/transportservice/action/%s.do",ZjFinal.ip,zjObject.getClass().getSimpleName().substring(2));
        String return_str_json = "";
        try {
            URL url = new URL(str_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type","html/text");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            String str_json = zjObject.toJsonString();
            Log.i("tag","发送json"+str_json);
            dos.write(str_json.getBytes());
            int code = connection.getResponseCode();
            if (code == 200){
                InputStream is = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int length = 0;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((length = is.read(buffer)) != -1){
                    baos.write(buffer,0,length);
                }
                return_str_json = baos.toString();
            }else {
                return_str_json = "{'RESULT':'F','ERRMSG':'code="+code+"'}";
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (return_str_json.equals("")){
            return_str_json = "{'RESULT':'F','ERRMSG':'返回json为空'}";
        }

        try {
            JSONObject jsonObject = new JSONObject(return_str_json);
        } catch (JSONException e) {
            return_str_json = "{'RESULT':'F','ERRMSG':'json转换失败'}";
            e.printStackTrace();
        }

        Log.i("tag","http-json:" + return_str_json);

        JSONObject return_jsonOject = null;
        try {
            return_jsonOject = new JSONObject(return_str_json);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return return_jsonOject;
    }
}
